import {defineStore} from "pinia";
import {CacheUtil} from "@/utils/cacheUtil.js";
import {LoginApi} from "@/api/login/index.js";

const loginUserStore = defineStore('loginUseStore', {
  state: () => ({
    token: CacheUtil.getToken(),
    userInfo: CacheUtil.getUserInfo(),
    roles: []
  }),
  getters: {},
  actions: {
    login(data) {
      return new Promise(async (resolve, reject) => {
        await LoginApi.login(data).then(res => {
          const {loginToken} = res.data;
          if (loginToken) {
            CacheUtil.setToken(loginToken);
            this.token = loginToken;
          }
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    getUserInfo() {
      return new Promise(async (resolve, reject) => {
        await LoginApi.getUserInfo().then(res=> {
          if (res.data) {
            CacheUtil.setUserInfo(res.data);
            this.userInfo = res.data;
            this.roles = res.data.roles;
          }
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      })
    },
    setRoles() {
      if (CacheUtil.getToken()) {
        this.roles = [CacheUtil.getToken()];
        return true;
      }
      return false;
    },
    logout() {
      return new Promise(async (resolve, reject) => {
        await LoginApi.logout().then(res => {
          this.userInfo = {};
          this.roles = [];
          CacheUtil.clear();
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    }
  }
});
export default loginUserStore;